from threading import Lock

class StreamController:
    def __init__(self):
        self._flags = {}
        self._lock = Lock()
        # 用于存储流式输出结果
        self._stream_outputs = {}

    def start(self, user_id):
        """启动一个用户的流请求"""
        with self._lock:
            # 设置前先取消旧请求
            self._flags[user_id] = False
            self._flags[user_id] = True
            # 初始化输出缓存
            self._stream_outputs[user_id] = ""

    def stop(self, user_id):
        """停止一个用户的流请求"""
        with self._lock:
            self._flags[user_id] = False

    def is_active(self, user_id):
        """检查一个用户的流请求是否活跃"""
        return self._flags.get(user_id, False)
        
    def append_output(self, user_id, delta):
        """添加流式输出内容"""
        with self._lock:
            if user_id in self._stream_outputs:
                self._stream_outputs[user_id] += delta
                
    def get_output(self, user_id):
        """获取完整的流式输出内容"""
        with self._lock:
            return self._stream_outputs.get(user_id, "")

# 全局实例
stream_controller = StreamController() 